package com.ls.lserp.modules.produce.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.order.entity.ChangeMaterial;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.order.entity.SizeColorQuantity;
import com.ls.lserp.modules.order.entity.StyleFeedBack;
import com.ls.lserp.modules.produce.entity.ProduceLicense;
import com.ls.lserp.modules.produce.entity.ProduceNotice;
import com.ls.lserp.modules.produce.service.ProduceLicenseService;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/produce/license/")
public class ProduceLicenseController extends BaseController {

	
	@Autowired
	private ProduceLicenseService produceLicenseService;
	
	
	@Autowired
	Configuration freemarkerConfiguration;
	@ModelAttribute
	public ProduceLicense get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return produceLicenseService.findByID(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new ProduceLicense();
		}
	}
	
	/**
	 * 采购预付款一览画面
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = {"searchList", "" })
	public String produceLicense(ProduceLicense produceLicense,Model model) {
		List<ProduceLicense> groupList = produceLicenseService.findGroupList();
		List<ProduceLicense> pList = produceLicenseService.findProduceNoticeList(produceLicense);
		model.addAttribute("groupList",groupList);
		model.addAttribute ("licenseList", pList);
        model.addAttribute("ognizationName",produceLicense.getOgnizationName());
        model.addAttribute("userGroupID",produceLicense.getUserGroupID());
        model.addAttribute("dateStart",produceLicense.getDateStart());
        model.addAttribute("dateEnd",produceLicense.getDateEnd());
		return "modules/produce/produceLicense";

	}
	
	/**
	 * 拼接一览画面
	 * @param values 
	 * 
	 * 
	 * @return
	 */
	/*@RequiresPermissions("produce:license:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(ProduceLicense produceLicense, HttpServletRequest request, HttpServletResponse response,
			Model model, String[] values) throws Exception {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			// ajax回调时使用的一览list名
			request.setAttribute("listNames", "produceLicense");
			// 画面取得的检索项目
			long userGroupID = produceLicense.getUserGroupID();
			String ognizationName = produceLicense.getOgnizationName();
			String dateStart = produceLicense.getDateStart();
			String dateEnd = produceLicense.getDateEnd();
			String ulSelected = produceLicense.getUlSelected();
			// 拼接字符串供分页使用
			String searchParam = "&userGroupID=" + userGroupID+"&ognizationName=" + ognizationName+"&dateStart=" + dateStart+"&dateEnd="+ dateEnd+"&ulSelected="+ ulSelected;
			//放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam);
			// 查询一览页面数据
			Page<ProduceLicense> page = produceLicenseService.findProduceNoticeList(new Page<ProduceLicense>(request, response),
					produceLicense);
			// 读取文件生成字符串
			String strUri = request.getContextPath() + Global.getAdminPath();
			String strHtml = "";
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("licenseList", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			map.put("springMacroRequestContext", new RequestContext (request));
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("produceLicenseList.ftl"), map);
			listMap.put("produceLicense", strHtml);
			listMap.put("page", page.getHtml());
			// ajax返回结果
			return renderString(response, listMap);
		}*/
	
	
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	 * 进入编辑页面
	 * @param orderMateriel
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = "form")
	public String form(ProduceLicense produceLicense,Model model) {
		
		List<ProduceLicense> indentList = produceLicenseService.findIndentNOList(produceLicense.getOgnizationID());
		produceLicense.setIndentList(indentList);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("produceLicense", produceLicense);
		// 返回页面地址
		return "modules/produce/produceLicenseCreate";
	}
	
	/**
	 * 订单联动获取各种数据
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = "findAnyInfo")
	public String findAnyInfo(ProduceLicense produceLicense,Model model) {
		BigcargoOrder bigcargoOrder = produceLicenseService.getIndentInfo(produceLicense);
		List<SizeColorQuantity> sizeColorQuantity = produceLicenseService.findSizeColor(produceLicense);
		List<ChangeMaterial> changeMaterial = produceLicenseService.findMaterial(produceLicense);
		List<StyleFeedBack> styleFeedBack = produceLicenseService.findFeedBack(produceLicense);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("bigcargoOrder", bigcargoOrder);
		model.addAttribute("sizeColorQuantity", sizeColorQuantity);
		model.addAttribute("changeMaterial", changeMaterial);
		model.addAttribute("styleFeedBack", styleFeedBack);
		// 返回页面地址
		return "modules/produce/produceLicenseCreate";
	}
	
	/**
	 * 创建采购预付款信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = {"createLicense"})
	public String createLicense(ProduceLicense produceLicense,Model model){
		List<ProduceLicense> customerList = produceLicenseService.findCustomerList();
		List<ProduceLicense> groupList = produceLicenseService.findGroupList();
		produceLicense.preInsert();
		produceLicense.setCustomerList(customerList);
		produceLicense.setGroupList(groupList);
		model.addAttribute("produceLicense",produceLicense);
		return "modules/produce/produceLicenseCreate";
	}
	
	/**
	 * 查看一条生产制单信息
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:license:view")
	@RequestMapping(value = {"viewLicense"})
	public String viewLicense(ProduceLicense produceLicense,Model model){
		ProduceNotice produceNotice = new ProduceNotice();
		produceLicense = produceLicenseService.getLicense(produceLicense);
		//如果通知单ID不为0则该制单存在关联的生产通知单
		if (produceLicense.getNoticeID() != 0) {
			produceNotice.setId(produceLicense.getNoticeID());
			//设置大货定制区分，大货为0，定制为1
			if (produceLicense.getProFlag() == 1) {
				produceNotice.setNoticeFlag("1");
			}else {
				produceNotice.setNoticeFlag("0");
			}
			produceNotice = produceLicenseService.getNotice(produceNotice);
			model.addAttribute("produceNotice", produceNotice);
			produceLicense.setSourceNotice("true");
			model.addAttribute ("groupList", produceLicense.getGroupList());
			model.addAttribute ("orderMateriel", produceNotice.getOrderMateriel ());
		}
		List<SizeColorQuantity> sizeColorQuantity = produceLicenseService.findSizeColor(produceLicense);
		List<ChangeMaterial> changeMaterial = produceLicenseService.findMaterial(produceLicense);
		List<StyleFeedBack> styleFeedBack = produceLicenseService.findFeedBack(produceLicense);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("sizeColorQuantity", sizeColorQuantity);
		model.addAttribute("changeMaterial", changeMaterial);
		model.addAttribute("styleFeedBack", styleFeedBack);
		model.addAttribute("produceLicense",produceLicense);
		return "modules/produce/produceLicenseShow";
	}
	/**
	 * 编辑生产制单信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("produce:License:view")
	@RequestMapping(value = {"editLicense"})
	public String editLicense(ProduceLicense produceLicense,Model model){
		ProduceNotice produceNotice = new ProduceNotice();
		produceLicense = produceLicenseService.getLicense(produceLicense);
		//如果通知单ID不为0则该制单存在关联的生产通知单
		if (produceLicense.getNoticeID() != 0) {
			produceNotice.setId(produceLicense.getNoticeID());
			//设置大货定制区分，大货为0，定制为1
			if (produceLicense.getProFlag() == 1) {
				produceNotice.setNoticeFlag("1");
			}else {
				produceNotice.setNoticeFlag("0");
			}
			produceNotice = produceLicenseService.getNotice(produceNotice);
			model.addAttribute("produceNotice", produceNotice);
			produceLicense.setSourceNotice("true");
			model.addAttribute ("groupList", produceLicense.getGroupList());
			model.addAttribute ("orderMateriel", produceNotice.getOrderMateriel ());
		}
		List<SizeColorQuantity> sizeColorQuantity = produceLicenseService.findSizeColor(produceLicense);
		List<ChangeMaterial> changeMaterial = produceLicenseService.findMaterial(produceLicense);
		List<StyleFeedBack> styleFeedBack = produceLicenseService.findFeedBack(produceLicense);
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("sizeColorQuantity", sizeColorQuantity);
		model.addAttribute("changeMaterial", changeMaterial);
		model.addAttribute("styleFeedBack", styleFeedBack);
		model.addAttribute("produceLicense",produceLicense);
		return "modules/produce/produceLicenseCreate";
	}
	
	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("produce:license:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(ProduceLicense produceLicense, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(produceLicense.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			ProduceLicense produceLicenseNew = get(produceLicense.getId().toString());
			// 判断数据是否删除
            if(produceLicenseNew==null || BaseEntity.DEL_FLAG_DELETE.equals(produceLicenseNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
            }
			
            // 排他处理
		    if(produceLicense.getVersion()==get(produceLicense.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	produceLicense.setVersion(produceLicense.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		    }
		}
		    // 保存数据
		produceLicenseService.saveProduceLicense(produceLicense);

			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));
	}

}
